<?php

/**
 * Name: 值班管理控制器
 * User: Silent
 * Date: 2025-11-07
 * Time: 16:30:00
 */

namespace App\Http\Controllers\V1\Resources\Checkin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Checkin\DutyRequest;
use App\Services\Checkin\DutyService;
use Illuminate\Http\Request;
use Exception;

class DutyController extends Controller
{
    protected $dutyService;

    public function __construct(DutyService $dutyService)
    {
        $this->dutyService = $dutyService;
    }

    /**
     * 设置当班班长
     * POST /api/v1/duty/leader/set
     */
    public function setLeader(DutyRequest $request)
    {
        try {
            $employee = $request->input('current_user');

            // 验证是否为主管权限
            if (!$this->isLeader($employee)) {
                return $this->_error('您没有权限设置当班班长');
            }

            $dutyData = $request->validated();

            $result = $this->dutyService->setDutyLeader($dutyData);

            if ($result['success']) {
                return $this->_success($result['message'], $result['data']);
            } else {
                return $this->_error($result['message']);
            }

        } catch (Exception $e) {
            return $this->_error('设置当班班长失败：' . $e->getMessage());
        }
    }

    /**
     * 设置值班领导
     * POST /api/v1/duty/supervisor/set
     */
    public function setSupervisor(DutyRequest $request)
    {
        try {
            $employee = $request->input('current_user');

            // 验证是否为主管权限
            if (!$this->isSupervisor($employee)) {
                return $this->_error('您没有权限设置值班领导');
            }

            $dutyData = $request->validated();
            $date = $request->input('date', today()->format('Y-m-d'));

            $result = $this->dutyService->setDutySupervisor($dutyData, $date);

            if ($result['success']) {
                return $this->_success($result['message'], $result['data']);
            } else {
                return $this->_error($result['message']);
            }

        } catch (Exception $e) {
            return $this->_error('设置值班领导失败：' . $e->getMessage());
        }
    }

    /**
     * 获取当班班长列表
     * GET /api/v1/duty/leader/list
     */
    public function leaderList(Request $request)
    {
        try {
            $employee = $request->input('current_user');
            $date = $request->input('date');
            $perPage = $request->input('per_page', 15);

            // 根据用户角色控制访问权限
            if (!$this->hasViewPermission($employee)) {
                return $this->_error('您没有权限查看当班班长信息');
            }

            $filters = $this->buildFilters($request);
            $result = $this->dutyService->getDutyLeadersList($date, $perPage, $filters);

            if ($result['success']) {
                return $this->_success('获取成功', $result['data']);
            } else {
                return $this->_error($result['message']);
            }

        } catch (Exception $e) {
            return $this->_error('获取当班班长列表失败：' . $e->getMessage());
        }
    }

    /**
     * 获取值班领导列表
     * GET /api/v1/duty/supervisor/list
     */
    public function supervisorList(Request $request)
    {
        try {
            $employee = $request->input('current_user');
            $date = $request->input('date');
            $perPage = $request->input('per_page', 15);

            // 根据用户角色控制访问权限
            if (!$this->hasViewPermission($employee)) {
                return $this->_error('您没有权限查看值班领导信息');
            }

            $filters = $this->buildFilters($request);
            $result = $this->dutyService->getDutySupervisorsList($date, $perPage, $filters);

            if ($result['success']) {
                return $this->_success('获取成功', $result['data']);
            } else {
                return $this->_error($result['message']);
            }

        } catch (Exception $e) {
            return $this->_error('获取值班领导列表失败：' . $e->getMessage());
        }
    }

    /**
     * 获取可选班长列表
     * GET /api/v1/duty/available-leaders
     */
    public function availableLeaders(Request $request)
    {
        try {
            $employee = $request->input('current_user');

            // 验证是否为权限
            if (!$this->isLeader($employee)) {
                return $this->_error('您没有权限查看班长列表');
            }

            $teamName = $request->input('team_name');
            $result = $this->dutyService->getAvailableLeaders($employee, $teamName);

            if ($result['success']) {
                return $this->_success('获取成功', $result['data']);
            } else {
                return $this->_error($result['message']);
            }

        } catch (Exception $e) {
            return $this->_error('获取班长列表失败：' . $e->getMessage());
        }
    }

    /**
     * 获取可选主管列表
     * GET /api/v1/duty/available-supervisors
     */
    public function availableSupervisors(Request $request)
    {
        try {
            $employee = $request->input('current_user');

            // 验证是否为主管权限
            if (!$this->isSupervisor($employee)) {
                return $this->_error('您没有权限查看主管列表');
            }

            $result = $this->dutyService->getAvailableSupervisors();

            if ($result['success']) {
                return $this->_success('获取成功', $result['data']);
            } else {
                return $this->_error($result['message']);
            }

        } catch (Exception $e) {
            return $this->_error('获取主管列表失败：' . $e->getMessage());
        }
    }

    /**
     * 获取今日值班信息
     * GET /api/v1/duty/today
     */
    public function today(Request $request)
    {
        try {
            $employee = $request->input('current_user');

            // 根据用户角色控制访问权限
            if (!$this->hasViewPermission($employee)) {
                return $this->_error('您没有权限查看值班信息');
            }

            $result = $this->dutyService->getTodayDutyInfo();

            if ($result['success']) {
                return $this->_success('获取成功', $result['data']);
            } else {
                return $this->_error($result['message']);
            }

        } catch (Exception $e) {
            return $this->_error('获取今日值班信息失败：' . $e->getMessage());
        }
    }

    /**
     * 自动生成下一工作日当班班长
     * POST /api/v1/duty/auto-generate
     */
    public function autoGenerate(Request $request)
    {
        try {
            $employee = $request->input('current_user');

            // 验证是否为主管权限
            if (!$this->isSupervisor($employee)) {
                return $this->_error('您没有权限执行自动生成操作');
            }

            $result = $this->dutyService->autoGenerateNextWorkday();

            if ($result['success']) {
                return $this->_success($result['message'], $result['data']);
            } else {
                return $this->_error($result['message']);
            }

        } catch (Exception $e) {
            return $this->_error('自动生成失败：' . $e->getMessage());
        }
    }

    /**
     * 获取值班人员详情
     * GET /api/v1/duty/supervisor/detail
     */
    public function supervisorDetail(Request $request)
    {
        try {
            $employee = $request->input('current_user');

            // 根据用户角色控制访问权限
            if (!$this->hasViewPermission($employee)) {
                return $this->_error('您没有权限查看值班人员详情');
            }

            // 获取 supervisor_id 参数
            $supervisorId = $request->input('supervisor_id');
            if (!$supervisorId) {
                return $this->_error('请提供值班人员ID');
            }

            $result = $this->dutyService->getSupervisorDetail($supervisorId);

            if ($result['success']) {
                return $this->_success('获取成功', $result['data']);
            } else {
                return $this->_error($result['message']);
            }

        } catch (Exception $e) {
            return $this->_error('获取值班人员详情失败：' . $e->getMessage());
        }
    }

    /**
     * 检查是否为主管
     */
    private function isSupervisor($employee)
    {
        $position = $employee->position;
        return in_array($position, ['主管', '部长', '副主管', '副部长']);
    }

    /**
     * 检查是否为班长
     * 注意：副班长不属于班长权限，只有班长、组长才有 leader 权限
     */
    private function isLeader($employee)
    {
        $position = $employee->position;
        return in_array($position, ['班长', '组长']);
    }

    /**
     * 检查是否有查看权限
     */
    private function hasViewPermission($employee)
    {
        return $this->isSupervisor($employee) || $this->isLeader($employee);
    }

    /**
     * 构建筛选条件
     */
    private function buildFilters($request)
    {
        $filters = [];

        if ($request->has('start_date')) {
            $filters['start_date'] = $request->input('start_date');
        }

        if ($request->has('end_date')) {
            $filters['end_date'] = $request->input('end_date');
        }

        if ($request->has('team_name')) {
            $filters['team_name'] = $request->input('team_name');
        }

        if ($request->has('leader_id')) {
            $filters['leader_id'] = $request->input('leader_id');
        }

        if ($request->has('supervisor_id')) {
            $filters['supervisor_id'] = $request->input('supervisor_id');
        }

        return $filters;
    }
}
